const Koa = require('koa'),
    route = require('koa-route'),
    websockify = require('koa-websocket');
const ip = require('ip');

const wsOptions = {};
const app = websockify(new Koa(), wsOptions);

let count = 0
let ctxs = []
let myip = ip.address()
let ips = []
app.ws.use(route.all('/', (ctx) => {
    // the websocket is added to the context as `ctx.websocket`.
    // if (ips.indexOf(myip) === -1) {//限制重复ip加入
        ips.push(myip)
        ctxs.push(ctx)
        ctx.websocket.on('message', function (message) {
            // print message from the client
            count++;
            console.log(ips);
            //发送给所以连接用户
            for (let i = 0; i < ctxs.length; i++) {
                ctxs[i].websocket.send('c-' + count);
                ctxs[i].websocket.send('ip-' + ips);
            }
        });

        ctx.websocket.on('close', function (message) {
            // print message from the client
            count--;
            console.log(count);
            //发送给所以连接用户
            let del = ips.indexOf(myip);//移出ip池
            ips.splice(del, 1);
            console.log(ips);
            for (let i = 0; i < ctxs.length; i++) {
                ctxs[i].websocket.send('c-' + count);
                ctxs[i].websocket.send('ip-' + ips);
            }
        });
    // } else {
    //     ctx.websocket.on('message', function (message) {
    //         // print message from the client
    //         //发送给当前连接用户
    //         ctx.websocket.send('c-' + count);
    //         ctx.websocket.send('ip-' + ips);

    //     });
    // }
}));
console.log('[demo] start-quick is starting at port 3003')
app.listen(3003);
